package com.limetalks.servlet;

import java.io.IOException;

import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limetalks.dao.StreamDAO;
import com.limetalks.data.Category;
import com.limetalks.data.Comment;
import com.limetalks.data.User;
import com.limetalks.util.GlobalStrings;

/**
 * Servlet implementation class AddCommentServlet
 */
public class AddCommentServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
	private StreamDAO streamDao;
	
    public AddCommentServlet() {
        super();
        streamDao = new StreamDAO(Persistence.createEntityManagerFactory(GlobalStrings.PERSISTENCE_UNIT_NAME));
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Integer streamId = Integer.valueOf(request.getParameter("stream"));
		Object user = request.getSession().getAttribute("user");
		String text = request.getParameter("text");
		
		if(user != null) {		
			Comment comment = new Comment();
			comment.setAuthorId(((User)user).getId());
			comment.setStreamId(streamId);
			comment.setText(text);
			streamDao.saveComment(comment);
			response.sendRedirect("stream.jsp?streamId=" + streamId);
			
		} else {
			request.getSession().setAttribute("error","Login to perform the action.");
			response.sendRedirect("error.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
